<template>
  <div id="wrongQuestionPage">
    <a-card :bordered="false" class="main-card">
      <div class="header">
        <h1 class="title">我的错题集</h1>
        <div class="description">
          这里展示了您在测试中的错误答案和AI智能分析
        </div>
      </div>

      <a-divider />

      <div v-if="loading" class="loading-container">
        <a-spin tip="加载中..." />
      </div>

      <div v-else-if="wrongQuestions.length === 0" class="empty-container">
        <a-empty description="暂无错题记录" />
      </div>

      <div v-else class="questions-container">
        <a-collapse accordion>
          <a-collapse-item
            v-for="(item, index) in wrongQuestions"
            :key="item.id"
            :header="`错题 ${index + 1}: ${
              item.questionContent?.title || '未知题目'
            }`"
          >
            <div class="question-content">
              <a-descriptions :column="1" bordered>
                <a-descriptions-item label="题目内容">
                  <div class="question-title">
                    {{ item.questionContent?.title || "未知题目" }}
                  </div>
                  <!-- 显示题目选项 -->
                  <div
                    v-if="
                      item.questionContent?.options &&
                      item.questionContent.options.length > 0
                    "
                    class="question-options"
                  >
                    <div
                      v-for="option in item.questionContent.options"
                      :key="option.key"
                      class="option-item"
                    >
                      <span class="option-key">{{ option.key }}:</span>
                      {{ option.value }}
                    </div>
                  </div>
                </a-descriptions-item>
                <a-descriptions-item label="用户答案">
                  <a-tag color="red">{{ item.userAnswer }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="正确答案">
                  <a-tag color="green">{{ item.correctAnswer }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="AI错误分析">
                  <div
                    class="error-analysis"
                    v-if="parseAnalysis(item.errorAnalysis)"
                  >
                    <div class="error-reason">
                      <h4>错误原因分析：</h4>
                      <p>{{ parseAnalysis(item.errorAnalysis).errorReason }}</p>
                    </div>
                    <div
                      class="knowledge-points"
                      v-if="parseAnalysis(item.errorAnalysis).knowledgePoints"
                    >
                      <h4>关联知识点：</h4>
                      <a-space direction="vertical">
                        <p
                          v-for="(point, i) in parseAnalysis(item.errorAnalysis)
                            .knowledgePoints"
                          :key="i"
                        >
                          {{ i + 1 }}. {{ point }}
                        </p>
                      </a-space>
                    </div>
                    <div
                      class="suggestions"
                      v-if="parseAnalysis(item.errorAnalysis).suggestions"
                    >
                      <h4>改进建议：</h4>
                      <a-space direction="vertical">
                        <p
                          v-for="(suggestion, i) in parseAnalysis(
                            item.errorAnalysis
                          ).suggestions"
                          :key="i"
                        >
                          {{ i + 1 }}. {{ suggestion }}
                        </p>
                      </a-space>
                    </div>
                  </div>
                  <div v-else>
                    <p>{{ item.errorAnalysis }}</p>
                  </div>
                </a-descriptions-item>
                <a-descriptions-item label="创建时间">
                  {{ formatDate(item.createTime) }}
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </a-collapse-item>
        </a-collapse>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { listWrongQuestionsUsingGet } from "@/api/wrongQuestionController";
import { useLoginUserStore } from "@/store/userStore";
import message from "@arco-design/web-vue/es/message";
import dayjs from "dayjs";

// 存储错题列表
const wrongQuestions = ref<API.WrongQuestionVO[]>([]);
// 加载状态
const loading = ref(true);
// 用户信息
const userStore = useLoginUserStore();

/**
 * 加载错题数据
 */
const loadWrongQuestions = async () => {
  loading.value = true;
  try {
    const userId = userStore.loginUser?.id;
    if (!userId) {
      message.error("请先登录");
      loading.value = false;
      return;
    }

    const res = await listWrongQuestionsUsingGet({
      userId: userId as number,
    });

    if (res.data.code === 0) {
      wrongQuestions.value = res.data.data || [];
      console.log("错题列表:", wrongQuestions.value);
    } else {
      message.error("获取错题失败：" + res.data.message);
    }
  } catch (error) {
    console.error("加载错题失败", error);
    message.error("加载错题失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

/**
 * 解析AI错误分析JSON（处理可能的非JSON格式）
 */
const parseAnalysis = (analysis: string | undefined) => {
  if (!analysis) return null;

  try {
    // 尝试解析JSON
    return JSON.parse(analysis);
  } catch (e) {
    // 如果不是有效的JSON，尝试解析文本
    const result: Record<string, any> = {
      errorReason: "",
      knowledgePoints: [],
      suggestions: [],
    };

    // 简单的文本分割处理
    if (analysis.includes("错误原因分析：")) {
      const parts = analysis.split(/关联知识点：|改进建议：/);

      if (parts.length > 0) {
        result.errorReason = parts[0].replace("错误原因分析：", "").trim();
      }

      if (parts.length > 1) {
        const knowledgeText = parts[1].trim();
        result.knowledgePoints = extractNumberedList(knowledgeText);
      }

      if (parts.length > 2) {
        const suggestionsText = parts[2].trim();
        result.suggestions = extractNumberedList(suggestionsText);
      }

      return result;
    }

    // 如果无法解析，直接返回原文本
    return { errorReason: analysis };
  }
};

/**
 * 从文本中提取编号列表
 */
const extractNumberedList = (text: string) => {
  const lines = text.split("\n");
  const items: string[] = [];

  for (const line of lines) {
    const trimmed = line.trim();
    // 匹配类似 "1. 内容" 或 "1.**内容**" 的格式
    if (/^\d+\./.test(trimmed)) {
      const item = trimmed.replace(/^\d+\.\s*/, "").replace(/\*\*/g, "");
      items.push(item.trim());
    }
  }

  return items;
};

/**
 * 格式化日期
 */
const formatDate = (date: string | undefined) => {
  if (!date) return "";
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 页面加载时获取错题数据
onMounted(() => {
  loadWrongQuestions();
});
</script>

<style scoped>
#wrongQuestionPage {
  padding: 16px;
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.header {
  margin-bottom: 24px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: var(--color-text-1);
}

.description {
  color: var(--color-text-3);
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.questions-container {
  margin-top: 16px;
}

.question-content {
  padding: 8px 0;
}

.error-analysis {
  margin-top: 8px;
}

.error-reason,
.knowledge-points,
.suggestions {
  margin-bottom: 16px;
}

.error-reason h4,
.knowledge-points h4,
.suggestions h4 {
  margin: 0 0 8px 0;
  color: var(--color-text-2);
  font-weight: 500;
}

/* 添加一些颜色区分 */
.error-reason {
  color: #f53f3f;
}

.knowledge-points {
  color: #165dff;
}

.suggestions {
  color: #00b42a;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-1);
  line-height: 1.6;
  margin-bottom: 8px;
}

.question-options {
  margin-top: 8px;
}

.option-item {
  margin-bottom: 4px;
  line-height: 1.6;
}

.option-key {
  font-weight: 500;
  margin-right: 8px;
}
</style>
